<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { getMenuListAsync, getOneMenuList, addMenuAsync, updateMenuAsync } from '@/api/services/MenuService'
import type { Menu } from '@/types/Menu'
import { getIconComponent } from '@/utils/icons'

// 响应数据
const menuList = ref<Menu[]>([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const currentMenuId = ref<number | null>(null)

// 表单数据
const form = reactive({
  id: 0,
  path: '',
  code: '',
  component: '',
  meta: {
    title: '',
    icon: '',
    isVisible: true,
    isEnabled: true,
    menuType: 1,
    sortIndex: 1,
    description: ""
  },
  parentId: 0
})

// 表单引用
const formRef = ref<FormInstance>()

// 表单验证规则
const rules = reactive<FormRules>({
  path: [
    { required: true, message: '请输入菜单路径', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入菜单编码', trigger: 'blur' }
  ],
  component: [
    { required: true, message: '请输入组件名称', trigger: 'blur' }
  ],
  'meta.title': [
    { required: true, message: '请输入菜单标题', trigger: 'blur' }
  ],
  'meta.icon': [
    { required: true, message: '请输入菜单图标', trigger: 'blur' }
  ]
})

// 菜单类型选项
const menuTypeOptions = [
  { label: '目录', value: 1 },
  { label: '菜单', value: 2 }
]

// 可见性选项
const visibleOptions = [
  { label: '显示', value: true },
  { label: '隐藏', value: false }
]

// 可见性选项
const enabledOptions = [
  { label: '启用', value: true },
  { label: '禁用', value: false }
]

// 父级菜单选项
const parentMenuOptions = ref<{ value: number; label: string }[]>([])

// 获取菜单列表
const fetchMenus = async () => {
  loading.value = true
  try {
    const params = {
      IsEnabled: searchForm.enabledOptions,
      IsVisible: searchForm.visibleOptions
    }
    const result = await getMenuListAsync(params)
    if (result.success) {
      // 更新菜单列表 - 使用类型断言将unknown[]转换为Menu[]
      menuList.value = result.data as Menu[]

      // 初始化父级菜单选项
      initParentMenuOptions(menuList.value)
    } else {
      ElMessage.error(`获取菜单列表失败: ${result.message}`)
    }
  } catch (error) {
    console.error('获取菜单列表失败:', error)
    ElMessage.error('获取菜单列表失败')
  } finally {
    loading.value = false
  }
}

// 获取一级菜单列表
const fetchOneMenuList = async () => {
  try {
    const result = await getOneMenuList()
    if (result.success) {
      // 根据返回结果格式处理数据
      const oneMenuList = result.data as { id: number; menuName: string }[]
      const options: { value: number; label: string }[] = [
        { value: 0, label: '根目录' }
      ]

      oneMenuList.forEach(menu => {
        options.push({
          value: menu.id,
          label: menu.menuName
        })
      })

      parentMenuOptions.value = options
    } else {
      ElMessage.error(`获取一级菜单列表失败: ${result.message}`)
    }
  } catch (error) {
    console.error('获取一级菜单列表失败:', error)
    ElMessage.error('获取一级菜单列表失败')
  }
}

// 初始化父级菜单选项
const initParentMenuOptions = (menus: Menu[]) => {
  const options: { value: number; label: string }[] = [
    { value: 0, label: '根目录' }
  ]

  const collectParentMenus = (menuList: Menu[]) => {
    menuList.forEach(menu => {
      if (menu.meta.menuType === 1) { // 只添加一级菜单作为父级选项
        options.push({
          value: menu.id,
          label: menu.meta.title
        })
      }
      if (menu.children && menu.children.length > 0) {
        collectParentMenus(menu.children)
      }
    })
  }

  collectParentMenus(menus)
  parentMenuOptions.value = options
}

// 打开添加菜单对话框
const openAddDialog = async () => {
  dialogTitle.value = '添加菜单'
  isEdit.value = false
  currentMenuId.value = null

  // 重置表单
  Object.assign(form, {
    id: 0,
    path: '',
    code: '',
    component: '',
    meta: {
      title: '',
      icon: '',
      isVisible: true,
      isEnabled: true,
      menuType: 1,
      sortIndex: 1
    },
    parentId: 0
  })

  // 获取一级菜单列表用于父级菜单选择
  await fetchOneMenuList()
  dialogVisible.value = true
}

// 打开编辑菜单对话框
const openEditDialog = async (menu: Menu) => {
  dialogTitle.value = '编辑菜单'
  isEdit.value = true
  currentMenuId.value = menu.id

  // 填充表单数据，使用parentMenuId作为父级ID
  Object.assign(form, {
    id: menu.id,
    path: menu.path,
    code: menu.code,
    component: menu.component,
    meta: {
      title: menu.meta.title,
      icon: menu.meta.icon,
      isVisible: menu.meta.isVisible,
      isEnabled: menu.meta.isEnabled,
      menuType: menu.meta.menuType,
      sortIndex: menu.meta.sortIndex,
      description: menu.meta.description
    },
    parentId: menu.parentMenuId || 0 // 使用parentMenuId作为父级ID，如果没有则为0（根目录）
  })

  // 获取一级菜单列表用于父级菜单选择
  await fetchOneMenuList()
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (isEdit.value && form.id) {
          // 修改菜单
          const addMenuParams = {
            Id: form.id,
            ParentMenuId: form.parentId,
            MenuName: form.meta.title,
            MenuCode: form.code,
            MenuType: form.meta.menuType,
            MenuPath: form.path,
            MenuIcon: form.meta.icon,
            ComponentName: form.component,
            SortIndex: form.meta.sortIndex,
            Description: form.meta.description,
            IsEnabled: form.meta.isEnabled,
            IsVisible: form.meta.isVisible
          }
          const result = await updateMenuAsync(addMenuParams)
          if (result.success) {
            ElMessage.success('菜单修改成功')

          } else {
            ElMessage.error(`添加修改失败: ${result.message}`)
            return
          }
        } else {
          // 添加菜单
          const addMenuParams = {
            ParentMenuId: form.parentId,
            MenuName: form.meta.title,
            MenuCode: form.code,
            MenuType: form.meta.menuType,
            MenuPath: form.path,
            MenuIcon: form.meta.icon,
            ComponentName: form.component,
            SortIndex: form.meta.sortIndex,
            Description: form.meta.description,
            IsEnabled: form.meta.isEnabled,
            IsVisible: form.meta.isVisible
          }

          const result = await addMenuAsync(addMenuParams)
          if (result.success) {
            ElMessage.success('菜单添加成功')
          } else {
            ElMessage.error(`添加菜单失败: ${result.message}`)
            return
          }
        }
        dialogVisible.value = false
        fetchMenus() // 刷新列表
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error(isEdit.value ? '更新菜单失败' : '添加菜单失败')
      }
    }
  })
}


// 删除菜单
const deleteMenu = async (menu: Menu) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除菜单 "${menu.meta.title}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    // 这里需要调用实际的删除API接口
    ElMessage.success('菜单删除成功')
    fetchMenus() // 刷新列表
  } catch {
    // 用户取消操作
  }
}

// 切换菜单可见性
const toggleVisible = async (menu: Menu) => {
  try {
    const newVisible = !menu.meta.isVisible
    const action = newVisible ? '显示' : '隐藏'

    await ElMessageBox.confirm(
      `确定要${action}菜单 "${menu.meta.title}" 吗？`,
      `${action}确认`,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    // 这里需要调用实际的更新API接口
    menu.meta.isVisible = newVisible
    ElMessage.success(`菜单${action}成功`)
  } catch {
    // 用户取消操作
  }
}

// 重置表单
const resetForm = () => {
  if (!formRef.value) return
  formRef.value.resetFields()
}

// 搜索相关数据
const searchForm = reactive({
  enabledOptions: true,
  visibleOptions: true
})

// 搜索菜单
const searchMenus = () => {
  fetchMenus()
}

// 获取父级菜单名称
const getParentMenuName = (parentMenuId: number): string => {
  const findMenuById = (menus: Menu[], id: number): Menu | null => {
    for (const menu of menus) {
      if (menu.id === id) {
        return menu
      }
      if (menu.children && menu.children.length > 0) {
        const found = findMenuById(menu.children, id)
        if (found) {
          return found
        }
      }
    }
    return null
  }

  const parentMenu = findMenuById(menuList.value, parentMenuId)
  return parentMenu ? parentMenu.meta.title : '未知菜单'
}


// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    enabledOptions: true,
    visibleOptions: true
  })
  fetchMenus()
}

// 页面加载时获取菜单列表
onMounted(() => {
  fetchMenus()
})
</script>

<template>
  <div class="menu-container">

    <!-- 搜索栏 - 单行布局 -->
    <el-card class="search-card">
      <div class="search-bar">
        <el-form :model="searchForm" label-width="auto" class="search-form">
          <div class="search-row">
            <el-form-item label="是否可见">
              <el-select v-model="searchForm.visibleOptions" placeholder="全部" clearable style="width: 120px">
                <el-option label="全部" value="" />
                <el-option v-for="item in visibleOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="是否启用">
              <el-select v-model="searchForm.enabledOptions" placeholder="全部" clearable style="width: 120px">
                <el-option label="全部" value="" />
                <el-option v-for="item in enabledOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <div class="search-actions">
              <el-button type="primary" @click="searchMenus" size="small">
                <el-icon>
                  <Search />
                </el-icon>
                搜索
              </el-button>
              <el-button @click="resetSearch" size="small">
                <el-icon>
                  <Refresh />
                </el-icon>
                重置
              </el-button>
            </div>
          </div>
        </el-form>
      </div>
    </el-card>

    <!-- 菜单列表 -->
    <div class="table-container">
      <el-card class="content-card">
        <template #header>
          <div class="table-header">
            <span>菜单列表</span>
            <div class="header-actions">
              <el-button type="primary" @click="openAddDialog">
                <el-icon>
                  <Plus />
                </el-icon>
                添加菜单
              </el-button>
              <el-button @click="fetchMenus">
                <el-icon>
                  <Refresh />
                </el-icon>
                刷新
              </el-button>
            </div>
          </div>
        </template>

        <div class="table-wrapper">
          <el-table :data="menuList" v-loading="loading" style="width: 100%" stripe row-key="id">
            <el-table-column prop="meta.title" label="菜单昵称" min-width="200" />
            <el-table-column prop="path" label="菜单路径" min-width="180" />
            <el-table-column prop="code" label="菜单编码" min-width="120" />
            <el-table-column prop="component" label="组件名称" min-width="150" />
            <el-table-column prop="meta.icon" label="菜单图标" width="100">
              <template #default="{ row }">
                <el-icon v-if="row.meta.icon">
                  <component :is="getIconComponent(row.meta.icon)" />
                </el-icon>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column prop="meta.menuType" label="菜单类型" width="100">
              <template #default="{ row }">
                <el-tag :type="row.meta.menuType === 1 ? 'primary' : 'success'">
                  {{ row.meta.menuType === 1 ? '一级菜单' : '二级菜单' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="meta.isVisible" label="是否可见" width="100">
              <template #default="{ row }">
                <el-tag :type="row.meta.isVisible ? 'success' : 'info'">
                  {{ row.meta.isVisible ? '显示' : '隐藏' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="meta.sortIndex" label="排序" width="80" />
            <el-table-column prop="parentMenuId" label="父级菜单" width="120">
              <template #default="{ row }">
                <span v-if="row.parentMenuId">
                  {{ getParentMenuName(row.parentMenuId) }}
                </span>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row }">
                <el-button size="small" @click="openEditDialog(row)">
                  修改
                </el-button>
                <el-button size="small" type="warning" @click="toggleVisible(row)">
                  {{ row.meta.isVisible ? '隐藏' : '显示' }}
                </el-button>
                <el-button size="small" type="danger" @click="deleteMenu(row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
    </div>

    <!-- 添加/编辑菜单对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" :close-on-click-modal="false">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="父级菜单" prop="parentId">
          <el-select v-model="form.parentId" placeholder="请选择父级菜单" style="width: 100%">
            <el-option v-for="item in parentMenuOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="菜单路径" prop="path">
          <el-input v-model="form.path" placeholder="请输入菜单路径" />
        </el-form-item>

        <el-form-item label="菜单编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入菜单编码" />
        </el-form-item>

        <el-form-item label="组件名称" prop="component">
          <el-input v-model="form.component" placeholder="请输入组件名称" />
        </el-form-item>

        <el-form-item label="菜单昵称" prop="meta.title">
          <el-input v-model="form.meta.title" placeholder="请输入菜单昵称" />
        </el-form-item>

        <el-form-item label="菜单图标" prop="meta.icon">
          <el-input v-model="form.meta.icon" placeholder="请输入菜单图标" />
        </el-form-item>

        <el-form-item label="菜单描述" prop="meta.description">
          <el-input v-model="form.meta.description" placeholder="请输入菜单描述" />
        </el-form-item>


        <el-form-item label="菜单类型" prop="meta.menuType">
          <el-radio-group v-model="form.meta.menuType">
            <el-radio v-for="item in menuTypeOptions" :key="item.value" :label="item.value">
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="是否可见" prop="meta.isVisible">
          <el-radio-group v-model="form.meta.isVisible">
            <el-radio v-for="item in visibleOptions" :key="item.value" :label="item.value">
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="是否启用" prop="meta.isEnabled">
          <el-radio-group v-model="form.meta.isEnabled">
            <el-radio v-for="item in enabledOptions" :key="item.value" :label="item.value">
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="排序序号" prop="meta.sortIndex">
          <el-input-number v-model="form.meta.sortIndex" :min="1" :max="999" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetForm">重置</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">
            {{ isEdit ? '更新' : '添加' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.menu-container {
  padding: 20px;
  height: calc(100vh - 40px);
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  overflow: hidden;
  position: relative;
  margin: 0;
  gap: 8px;
  max-height: calc(100vh - 40px);
}

h1 {
  color: #303133;
  margin-bottom: 16px;
  font-size: 24px;
  font-weight: 600;
}

p {
  color: #606266;
  margin-bottom: 24px;
  font-size: 14px;
}

/* 搜索栏样式 - 单行布局 */
.search-card {
  margin-bottom: 0;
  border-radius: 6px;
  box-shadow: 0 1px 4px 0 rgba(0, 0, 0, 0.08);
  flex-shrink: 0;
  overflow: visible;
  z-index: 20;
  position: relative;
  max-height: 80px;
  min-height: 80px;
  background: #fff;
}

.search-bar {
  padding: 12px 20px;
  position: relative;
  z-index: 15;
  background: #fff;
  border-radius: 6px;
  overflow: hidden;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  gap: 0;
  height: auto;
}

/* 搜索表单样式 - 单行布局 */
:deep(.search-form) {
  display: flex;
  flex-direction: column;
  gap: 0;
  width: 100%;
}

.search-row {
  display: flex;
  align-items: center;
  gap: 16px;
  width: 100%;
  flex-wrap: nowrap;
  justify-content: space-between;
}

:deep(.search-form .el-form-item) {
  margin-bottom: 0;
  display: flex;
  align-items: center;
  height: 36px;
  margin-right: 0;
  flex-shrink: 0;
}

:deep(.search-form .el-form-item__label) {
  line-height: 36px;
  padding-bottom: 0;
  font-size: 14px;
  margin-right: 8px;
  width: auto;
  display: flex;
  align-items: center;
  color: #606266;
  font-weight: 500;
  min-width: max-content;
  white-space: nowrap;
}

:deep(.search-form .el-input) {
  height: 36px;
  width: auto;
  flex-shrink: 0;
}

:deep(.search-form .el-input__inner) {
  height: 36px;
  line-height: 36px;
  font-size: 14px;
  width: 100%;
  padding: 0 12px;
}

:deep(.search-form .el-select) {
  height: 36px;
  width: auto;
  flex-shrink: 0;
}

:deep(.search-form .el-select .el-input__inner) {
  height: 36px;
  line-height: 36px;
  font-size: 14px;
  width: 100%;
  padding: 0 12px;
}

.search-actions {
  display: flex;
  align-items: center;
  gap: 12px;
  height: 36px;
  margin-left: auto;
  flex-shrink: 0;
}

:deep(.search-actions .el-button) {
  height: 36px;
  padding: 0 16px;
  font-size: 14px;
  min-width: 70px;
}

/* 表格容器样式 - 固定高度确保滚动条显示 */
.table-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
  overflow: hidden;
  position: relative;
  margin-top: 0;
  height: calc(100vh - 160px);
}

/* 表格包装器样式 - 固定高度和滚动设置 */
.table-wrapper {
  flex: 1;
  min-height: 0;
  overflow: hidden;
  position: relative;
  margin-top: 0;
  height: 100%;
  display: flex;
  flex-direction: column;
}

/* 表格样式 - 固定高度确保滚动条 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  width: 100%;
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
}

:deep(.el-table .el-table__header-wrapper) {
  flex-shrink: 0;
}

:deep(.el-table .el-table__body-wrapper) {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  max-height: 470px;
  /* 固定高度确保滚动条 */
}

/* 确保表格行高度合适 */
:deep(.el-table__row) {
  height: 48px;
}

:deep(.el-table .el-table__cell) {
  padding: 8px 0;
}

/* 表格标题样式 - 固定头部 */
.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: sticky;
  top: 0;
  background: inherit;
  z-index: 10;
}

/* 卡片内容区域样式 - 自适应高度 */
:deep(.el-card__body) {
  padding: 16px;
  margin-top: 0;
  height: auto;
  min-height: 0;
  overflow: visible;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

:deep(.el-table .cell) {
  display: flex;
  align-items: center;
}

:deep(.el-table .el-button) {
  margin-right: 8px;
}

:deep(.el-table .el-button:last-child) {
  margin-right: 0;
}

/* 固定表格头部和操作列 */
:deep(.el-table__header-wrapper) {
  position: sticky;
  top: 0;
  z-index: 10;
}

:deep(.el-table__fixed-header-wrapper) {
  position: sticky;
  top: 0;
  z-index: 11;
}

:deep(.el-table__fixed-right) {
  position: sticky;
  right: 0;
  z-index: 10;
}

:deep(.el-table__fixed-left) {
  position: sticky;
  left: 0;
  z-index: 10;
}

/* 对话框样式 */
:deep(.el-dialog) {
  border-radius: 12px;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid #ebeef5;
  padding: 20px 20px 10px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-dialog__footer) {
  border-top: 1px solid #ebeef5;
  padding: 10px 20px 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 按钮样式 */
:deep(.el-button) {
  border-radius: 6px;
}

:deep(.el-button--primary) {
  background-color: #409eff;
  border-color: #409eff;
}

:deep(.el-button--primary:hover) {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

/* 输入框样式 */
:deep(.el-input) {
  border-radius: 6px;
}

:deep(.el-input__inner) {
  border-radius: 6px;
}

/* 标签样式 */
:deep(.el-tag) {
  border-radius: 4px;
}

/* 卡片标题样式 */
:deep(.el-card__header) {
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  padding: 16px 20px;
  font-weight: 600;
  color: #303133;
  border-radius: 12px 12px 0 0;
  position: sticky;
  top: 0;
  z-index: 10;
}
</style>
